package com.cf.apiInstance.common.utils;

import java.io.IOException;

import com.cf.apiInstance.common.enums.ErrorCodeEnum;
import com.cf.apiInstance.exception.JsonParsingException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * fast json 解析工具类
 * 
 * @author: cf
 * @date: 28 Nov 2018 6:27:52 pm
 * @vesion: 1.0
 */
@Slf4j
public final class JsonUtils {

	private static ObjectMapper mapper = new ObjectMapper();

	/**
	 * 实体转json字符串
	 * 
	 * @param obj
	 * @return
	 * @throws JsonProcessingException
	 *             返回类型 String
	 */
	public static String toJson(Object obj) throws JsonParsingException{
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			log.error("转json出错:", e.getMessage(), e);
			throw new JsonParsingException(ErrorCodeEnum.MISSING_REQUIRED_ARGUMENTS, e);
		}
	}

	/**
	 * 将JSON字符串转换为对象
	 * 
	 * @param json
	 *            JSON字符串
	 * @param valueType
	 *            对象类型
	 * @return 对象
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	public static <T> T toObject(String json, Class<T> objClass) throws JsonParsingException{
		try {
			return mapper.readValue(json, objClass);
		} catch (JsonParseException e) {
			log.error("json解析出错:", e.getMessage(), e);
			throw new JsonParsingException(ErrorCodeEnum.MISSING_REQUIRED_ARGUMENTS, e);
		} catch (JsonMappingException e) {
			log.error("json解析出错:", e.getMessage(), e);
			throw new JsonParsingException(ErrorCodeEnum.MISSING_REQUIRED_ARGUMENTS, e);
		} catch (IOException e) {
			log.error("json解析出错:", e.getMessage(), e);
			throw new JsonParsingException(ErrorCodeEnum.MISSING_REQUIRED_ARGUMENTS, e);
		}
	}
}
